package com.chushouya.product.service.async;


import com.general.framework.core.utils.Threads;
import com.general.framework.web.utils.SpringUtils;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 异步任务管理器
 */
public class ProductAsyncManager {

    private static final int OPERATE_DELAY_TIME = 10; // 默认十毫秒

    /**
     * 异步操作任务调度线程池
     */
    private final ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

    /**
     * 单例模式
     */
    private ProductAsyncManager() {
    }

    private static final ProductAsyncManager me = new ProductAsyncManager();

    public static ProductAsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     * 延迟10ms
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行任务
     *
     * @param task     任务
     * @param delay    延迟数值
     * @param timeUnit 延迟时间单位
     */
    public void execute(TimerTask task, int delay, TimeUnit timeUnit) {
        executor.schedule(task, delay, timeUnit);
    }

    public void executeDelay1s(TimerTask task) {
        executor.schedule(task, 1, TimeUnit.SECONDS);
    }

    public void executeDelay3s(TimerTask task) {
        executor.schedule(task, 3, TimeUnit.SECONDS);
    }

    public void executeDelay5s(TimerTask task) {
        executor.schedule(task, 5, TimeUnit.SECONDS);
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        Threads.shutdownAndAwaitTermination(executor);
    }
}
